{extend name="public/base"/}
{block name="style"}
<link rel="stylesheet" href="__PUBLIC__/css/order.css">
<style>
    #product-more-btn {top: 30px;line-height: 30px;}
    #product-more-btn button { width: 100%;}
    .copy-sku{cursor:pointer;}
</style>
{/block}
{block name="content"}
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12 Order">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-tab">
                        <div class="layui-tab-content">
                            <div class="layui-tab-item screen-box">
                                <div class="layui-form-item channel product-select">
                                    <label class="layui-form-label">平台</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="platform_name="><a class="active">全部</a></li>
                                            {foreach name="platform" id="p"}
                                            <li item="platform_id={$p->platform_id}"><a>{$p->name}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item channel product-select">
                                    <label class="layui-form-label">生成时间</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="create_date="><a class="active">全部</a></li>
                                            {foreach name="create_date" id="create" key="key"}
                                            <li item="create_date={$key}"><a>{$create}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item channel product-select">
                                    <label class="layui-form-label">排序方式</label>
                                    <div class="layui-input-block">
                                        <ul>
                                            <li item="sort="><a class="active">默认</a></li>
                                            {foreach name="sort" id="st" key="key"}
                                            <li item="sort={$key}"><a>{$st}</a></li>
                                            {/foreach}
                                        </ul>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">SKU生成时间</label>
                                    <div class="layui-input-inline" style="width: 220px;">
                                        <input class="layui-input laydate-range" id="start_date" autocomplete="off" name="date" placeholder="录入时间">
                                    </div>
                                    <button type="button" class="layui-btn layui-btn layui-btn-normal search-btn"><i
                                            class="layui-icon layui-icon-search"></i></button>
                                </div>
                            </div>
                            <div class="layui-tab-item layui-show">
                                <form class="layui-form">
                                    <div class="layui-col-md1 layui-row">
                                        <select id="select_product" lay-search lay-filter="select_product">
                                            {foreach name="select_product" id="item" key="key"}
                                            <option value="{$key}">{$item}</option>
                                            {/foreach}
                                        </select>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <input id="product_name" placeholder="按回车搜索" class="layui-input"/>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <div id="product-category"></div>
                                    </div>
                                    <div class="layui-col-md1 layui-row">
                                        <select id="select_account" lay-search lay-filter="search">
                                            <option value="">销售账号</option>
                                            {foreach name="account" id="a"}
                                            <option value="{$a.account_id}">{$a.username ?: $a.store_name}</option>
                                            {/foreach}
                                        </select>
                                    </div>
                                    <div class="layui-col-md2 layui-row">
                                        <a class="layui-btn layui-btn-normal product-select-down"><span>更多</span>&nbsp;&nbsp;<i
                                                class="fa fa-angle-double-down" aria-hidden="true"></i></a>
                                    </div>
                                    {php}if(isset($other_filter)):{/php}
                                        {foreach name="other_filter" id="filter" key="f"}
                                            <input type="hidden" class="other-filter" name="{$f}" value="{$filter}"/>
                                        {/foreach}
                                    {php}endif;{/php}
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-btn-group">
                        <button type="button" id="remove-all" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-delete"></i>批量删除
                        </button>
                        <a href="/attachment/template/platform-sku-template.xlsx?v=1"
                           class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-download-circle"></i>下载模板</a>
                        <button type="button" id="import-product" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-upload-drag"></i>导入平台SKU
                        </button>
                        <button type="button" id="export-product" class="layui-btn layui-btn-sm layui-btn-normal"><i
                                class="layui-icon layui-icon-export"></i>导出平台SKU
                        </button>
                        <ul class="layui-nav layui-bg-green btnz"
                            style="font-size: 12px;border-radius: 0px;float: right;padding:0px;margin-left: 2px;">
                            <li class="layui-nav-item" style="line-height: 30px;font-size: 12px;">
                                <a class="layui-btn layui-btn-sm layui-btn-normal"
                                   style="color:white;font-size: 12px;padding: 0px 30px 0px 20px;">更多<span
                                        class="layui-nav-more" style="right: 10px;font-size: 12px;"></span></a>
                                <dl class="layui-nav-child" id="product-more-btn"> <!-- 二级菜单 -->
                                    <dd>
                                        <button type="button" id="batch-readd"
                                                class="layui-btn layui-btn-sm layui-btn-normal">再次生成
                                        </button>
                                    </dd>
                                </dl>
                            </li>
                        </ul>
                    </div>
                    <table class="layui-hide" id="commodity" lay-filter="commodity"></table>
                </div>
            </div>
        </div>
    </div>
<!--操作-->
<script type="text/html" id="operation">
    <div>
        <button style="margin-bottom: 3px;" lay-event="add" type="button" class="layui-btn layui-btn-sm"><i
            class="layui-icon layui-icon-add-circle"></i></button><br>
        <button type="button" lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger"><i
                class="layui-icon layui-icon-delete"></i></button>
    </div>
</script>
{/block}
{block name="script"}
<script type="text/javascript">
layui.extend({
    xmSelect: 'xm-select'
}).use('xmSelect');
layui.use(['form', 'laydate', 'table', 'upload', 'layer', 'longli', 'xmSelect'], function () {
    var form = layui.form
        , layer = layui.layer
        , laydate = layui.laydate
        , table = layui.table
        , upload = layui.upload;

    //展示已知数据
    table.render({
        elem: '#commodity'
        , page: true
        , url: '{:url("wms/platform/index")}?' + $.param(getOtherFilter())
        //, toolbar: '#toolbarDemo'
        , title: '平台SKU数据表'
        , height: 'full-200'
        , cols: [[ //标题栏
            {type: 'checkbox'},
            {
                field: 'image_url', title: '图片', width: 130, templet: function (row) {

                       return `<div><img class="carousel-img" src="${row.store.image_url}"></div>`;
                }
            }
            , {
                field: 'info', title: '商品名称', width: 350, templet: function (row) {
                    return `<p>中文名：${row.product.name_ch?row.product.name_ch:''}</p>
                            <p>英文名：${row.product.name_en?row.product.name_en:''}</p>
                           `;
                }
            }
            , {
                field: 'account', title: '账号', templet: function (row) {
                    return row.account.username ? row.account.username : row.account.store_name;
                }
            }
            ,{
                field: 'sku', title: 'SKU', templet: function (row) {
                    return `<span class="copy-text">${row.sku}</span>`;
                }
            }
            ,{
                field: 'platform_sku', title: '平台SKU', templet: function (row) {
                    return `<span class="copy-text">${row.platform_sku}</span>`;
                }
            }
            ,{field: 'status', width: 90, title: '状态', templet: function (row) {
                    return row.status == 1 ? '启用' : '关闭';
                }
             }
            , {
                field: 'create_time', title: '生成时间', width: 200
            }
            , {field: 'experience', title: '操作', width: 70, fixed: "right", toolbar: '#operation'}
        ]]
        //,skin: 'line' //表格风格
        , even: true
        , limits: [100, 150, 300, 500]
        , limit: 100 //每页默认显示的数量
    });

    // 加载产品分类多选
    var productCateogry = layui.xmSelect.render({
        el: '#product-category',
        prop: {
            name: "title",
            value: "id"
        },
        tree: {
            show: true,
            //是否展示三角图标
            showFolderIcon: true,
            //是否显示虚线
            showLine: false,
            //间距
            indent: 20,
            //默认展开节点的数组, 为 true 时, 展开所有节点
            expandedKeys: [1],
            //是否严格遵守父子模式
            strict: true,
            //是否开启极简模式
            simple: false,
        },
        name: "product-category",
        autoRow: true,
        data: [],
        on: function(data)
        {
            setTimeout(()=>{reloadSkuTable();}, 300);
        }
    });
    $.get('{:url("/wms/category/getTree")}').done(function(response)
    {
        if(response.code != 1)
        {
            layer.msg("分类加载失败", {icon: 5, time: 1500});
            return false;
        }
        productCateogry.update({data: response.data});
    });

    // 平台SKU搜索
    $(".search-btn").click(function () {
        var $where = {};
        $("div.product-select li a.active").each(function (i, e) {
            var item = $(e).parent().attr("item").split("=");
            if (item[1]) $where[item[0]] = item[1];
        });
        var cate = $("input[name='product-category']").val(),
            account = $("#select_account option:selected").val(),
            productVal = $("#product_name").val().trim(),
            start_date = $("#start_date").val().trim();
        if (productVal) $where[$("#select_product option:selected").val()] = productVal;
        if (cate) $where["category_id"] = cate;
        if (start_date) $where["start_date"] = start_date;
        if(account) $where["account_id"] = account;
        $where = $.extend($where, getOtherFilter());
        // if($.isEmptyObject($where)) return;
        var url = "{:url('/wms/platform/index')}" + ($.isEmptyObject($where) ? "" : "?" + $.param($where));
        table.reload("commodity", {
            url: url,
            page: {
                curr: 1 //重新从第 1 页开始
            },
            // where: $where,
            // done: function(){console.log(this.where);}
        });
        return false;
    });

    form.on('select(select_product)', function (data) {
        if ($("#product_name").val().trim() != "") reloadSkuTable();
    });
    form.on('select(search)', function (data) {
        if (data.value != "") reloadSkuTable();
    });

    // 监听输入框回车
    $("#product_name").keydown(function (event) {
        if (event.keyCode == 13) reloadSkuTable();
    });

    //监听行工具事件
    table.on('tool(commodity)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除平台SKU？', function (index) {
                deletePskus(data.pid, function () {
                    obj.del();
                    layer.close(index);
                });
            });
        }
        else if(obj.event === 'add')
        {
            let pid = data.pid;
            $.get("{:url('/wms/platform/readd')}",{pid}).done(function(response)
            {
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500}, function()
                {
                    reloadSkuTable();
                });
            });
        }
    });


    function getOtherFilter()
    {
        var other = {};
        $("input.other-filter").each(function()
        {
            other[$(this).attr("name")] = $(this).val();
        });
        return other;
    }
    // 刷新表格平台SKU
    function reloadSkuTable() {
        $(".search-btn").click();
        form.render('select');
    }

    /**
     * 删除平台SKU
     * @param productId  平台SKUid 可多个
     * @param fn 回调函数
     */
    function deletePskus(productId, fn) {
        $.get("{:url('wms/platform/delete')}", {ids: productId}).done(function (response) {
            var icon = response.code == 1 ? 6 : 5;
            if(response.code == 1)
            {
                layer.msg(response.msg, {icon: icon, time: 1500}, fn ? fn : null);
            }
            else
            {
                layer.msg(response.msg, {icon: icon, time: 1500});
            }
        });
    }

    // 导入平台SKU
    upload.render({
        elem: '#import-product'
        , url: '{:url("file/upload",["type"=>"document"])}'
        , accept: 'file' //普通文件
        , exts: 'xlsx|xls|csv' // 指定类型
        , field: "file"
        , before: function (obj) {
            layer.load(0, {shade: false});
        }
        , done: function (response, index, upload) {
            if (response.code != 1) {
                layer.closeAll('loading');
                var icon = response.code == 1 ? 6 : 5;
                layer.msg(response.msg, {icon: icon, time: 1500});
                return;
            }
            $.post("{:url('wms/platform/import')}", {"path": response.data.src}).done(function(response)
            {
                layer.closeAll('loading');
                var icon = 5, time = 5500;
                if (response.code == 1) {
                    icon = 6;
                    time = 1500;
                }
                layer.msg(response.msg.replace(/\n/g, "<br/>"), {icon, time}, function () {
                    if (response.code == 1) reloadSkuTable();
                });
            });
        }
        , error: function (index, upload) {
            layer.msg('上传失败');
        }
    });

    // 导出平台SKU
    $("#export-product").click(function () {
        var data = table.checkStatus("commodity").data;
        var ids = [];
        for (let i in data) ids.push(data[i].pid);
        var start_date = $("#start_date").val().trim();
        if (!data.length && !start_date) return layer.msg('请选择要导出的平台SKU');
        layer.load(0, {shade: false});
        $.get("{:url('wms/platform/export')}", {ids, start_date}).done(function (response) {
            layer.closeAll('loading');
            response.code == 1
                ? location.href = "{:url('file/download')}?file=" + response.data.src
                : layer.msg(response.msg, {icon: 5, time: 1500});
        });
    });

    // 批量删除平台SKU
    $("#remove-all").click(function () {
        var data = table.checkStatus("commodity").data,
            dataLen = data.length;
        if (!dataLen > 0) return layer.msg('请选择要删除的平台SKU');
        layer.confirm(`你真的要删除【${dataLen}】个平台SKU吗？`, {btn: ['确认删除', '取消']}, function (index) {
            var ids = [];
            for (let i in data) ids.push(data[i].pid);
            /*$("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function()
            {
                var n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove(); // 移除行
                //如果是全选移除，就将全选CheckBox还原为未选中状态
                $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
            });*/
            deletePskus(ids.join(","), function () {
                reloadSkuTable();
                layer.close(index);
            });
        });
    });

    // 批量再次生成平台SKU
    $("#batch-readd").click(function () {
        var data = table.checkStatus("commodity").data,
            dataLen = data.length;
        if (!dataLen > 0) return layer.msg('请选择要再次生成的平台SKU');
        var ids = [];
        for (let i in data) ids.push(data[i].pid);
        $.get("{:url('/wms/platform/readd')}",{pid : ids.join(",")}).done(function(response)
        {
            var icon = response.code == 1 ? 6 : 5;
            layer.msg(response.msg, {icon: icon, time: 1500}, function()
            {
                reloadSkuTable();
            });
        });
    });

    // 点击筛选平台SKU状态
    $("body").on("click", ".product-status-select li", function () {
        var $this = $(this);
        $this.siblings().find("a").removeClass("active");
        $this.find("a").addClass("active");
    });

    // 点击筛选
    $(".product-select li").click(function () {
        var $this = $(this);
        $this.siblings().find("a").removeClass("active");
        $this.find("a").addClass("active");
        reloadSkuTable();
    });

    // 展示更多筛选项
    $(".product-select-down").click(function () {
        var $this = $(this), $box = $(".screen-box");
        $box.toggle("fast");
        if ($box.data("c")) {
            $box.data("c", 0);
            $this.find("span").text("更多");
            $this.find("i").removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
        } else {
            $box.data("c", 1);
            $this.find("span").text("收起");
            $this.find("i").removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
        }
    });

    // 重置表格大小
    resetTableSize(table, "commodity");
});
</script>
{/block}
